{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#!/usr/bin/python\n",
    "import numpy as np\n",
    "import scipy.sparse\n",
    "import pickle\n",
    "import xgboost as xgb\n",
    "\n",
    "# 基本例子，从libsvm文件中读取数据，做二分类\n",
    "# 数据是libsvm的格式\n",
    "#1 3:1 10:1 11:1 21:1 30:1 34:1 36:1 40:1 41:1 53:1 58:1 65:1 69:1 77:1 86:1 88:1 92:1 95:1 102:1 105:1 117:1 124:1\n",
    "#0 3:1 10:1 20:1 21:1 23:1 34:1 36:1 39:1 41:1 53:1 56:1 65:1 69:1 77:1 86:1 88:1 92:1 95:1 102:1 106:1 116:1 120:1\n",
    "#0 1:1 10:1 19:1 21:1 24:1 34:1 36:1 39:1 42:1 53:1 56:1 65:1 69:1 77:1 86:1 88:1 92:1 95:1 102:1 106:1 116:1 122:1\n",
    "dtrain = xgb.DMatrix('../data/agaricus.txt.train')\n",
    "dtest = xgb.DMatrix('../data/agaricus.txt.test')\n",
    "\n",
    "#超参数设定\n",
    "param = {'max_depth':2, 'eta':1, 'silent':1, 'objective':'binary:logistic' }\n",
    "\n",
    "# 设定watchlist用于查看模型状态\n",
    "watchlist  = [(dtest,'eval'), (dtrain,'train')]\n",
    "num_round = 2\n",
    "bst = xgb.train(param, dtrain, num_round, watchlist)\n",
    "\n",
    "# 使用模型预测\n",
    "preds = bst.predict(dtest)\n",
    "\n",
    "# 判断准确率\n",
    "labels = dtest.get_label()\n",
    "print('错误率为%f' % \\\n",
    "       (sum(1 for i in range(len(preds)) if int(preds[i]>0.5)!=labels[i]) /float(len(preds))))\n",
    "\n",
    "# 模型存储\n",
    "bst.save_model('../../tmp/0001.model')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
